import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/article",
    name: "article",
    component: () => import("../views/Blogs.vue")
  },
  {
    path: "/project",
    name: "project",
    component: () => import("../views/Blogs.vue")
  },
  {
    path: "/detail",
    name: "detail",
    component: () => import("../views/Detail.vue")
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue")
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../views/Register.vue"),
    meta: {
      requireAuth: true
    }
  },
  {
    path: "/manage",
    name: "manage",
    component: () => import("../views/Manage.vue"),
    meta: {
      requireAuth: true
    }
  }
];

const router = new VueRouter({
  routes
});

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
router.beforeEach((to, from, next) => {
  // 判断当前路由是否需要权限
  if (to.matched.some(record => record.meta.requireAuth)) {
    // 判断当前是否存在 token
    if (sessionStorage.getItem("token")) {
      next();
    } else {
      next({
        path: "/login"
      });
    }
  } else {
    next();
  }
});

export default router;
